import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUserInfoAPI, logoutAPI } from '@/http/chatAPI'

export interface User {
  id: number
  uuid: string
  username: string
  email: string
  avatarUrl?: string
  subscriptionType: string
}

// Token存储接口
export interface TokenData {
  token: string
  expiresAt: number // 过期时间戳
  refreshToken?: string // 可选的刷新token
}

export const useUserStore = defineStore('user', () => {
  // 状态 - 这些会被自动持久化
  const user = ref<User | null>(null)
  const tokenData = ref<TokenData | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => {
    if (!tokenData.value) return false
    
    // 检查token是否过期
    const now = Date.now()
    if (now >= tokenData.value.expiresAt) {
      // token已过期，清除
      console.log('Token已过期，自动清除')
      clearUser()
      return false
    }
    
    return true
  })
  
  // 获取当前有效token
  const token = computed(() => {
    return isAuthenticated.value ? tokenData.value?.token || null : null
  })

  const isSubscribed = computed(() => user.value?.subscriptionType !== 'free')

  // 设置用户信息
  const setUser = (userData: User) => {
    user.value = userData
  }

  // 设置token（带过期时间）
  const setToken = (tokenValue: string, expiresInHours: number = 24, refreshToken?: string) => {
    const expiresAt = Date.now() + (expiresInHours * 60 * 60 * 1000) // 转换为毫秒
    
    tokenData.value = {
      token: tokenValue,
      expiresAt,
      refreshToken
    }
  }

  // 清除用户信息
  const clearUser = () => {
    user.value = null
    tokenData.value = null
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) {
      throw new Error('未登录')
    }

    try {
      const response = await getUserInfoAPI()
      // 确保返回数据符合User接口
      const userData = response as unknown as User
      setUser(userData)
      return userData
    } catch (error) {
      // 如果获取用户信息失败，可能token已过期
      clearUser()
      throw error
    }
  }

  // 登录
  const login = (tokenValue: string, userData: User, expiresInHours: number = 24, refreshToken?: string) => {
    setToken(tokenValue, expiresInHours, refreshToken)
    setUser(userData)
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await logoutAPI()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      clearUser()
    }
  }

  // 更新用户信息
  const updateUser = (userData: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...userData }
    }
  }

  // 获取token剩余时间（分钟）
  const getTokenRemainingTime = () => {
    if (!tokenData.value) return 0
    
    const now = Date.now()
    const remaining = tokenData.value.expiresAt - now
    
    return Math.max(0, Math.floor(remaining / (1000 * 60))) // 转换为分钟
  }

  // 检查token是否即将过期（默认30分钟内）
  const isTokenExpiringSoon = (thresholdMinutes: number = 30) => {
    const remainingMinutes = getTokenRemainingTime()
    return remainingMinutes <= thresholdMinutes && remainingMinutes > 0
  }

  // 刷新token（如果有refreshToken的话）
  const refreshToken = async () => {
    if (!tokenData.value?.refreshToken) {
      throw new Error('没有可用的刷新token')
    }

    try {
      // 这里应该调用刷新token的API
      // const response = await refreshTokenAPI(tokenData.value.refreshToken)
      // setToken(response.token, response.expiresInHours, response.refreshToken)
      
      console.log('Token刷新功能需要后端API支持')
      return true
    } catch (error) {
      console.error('刷新token失败:', error)
      clearUser()
      throw error
    }
  }

  // 初始化检查（检查持久化恢复的token是否有效）
  const checkTokenValidity = () => {
    if (tokenData.value) {
      const now = Date.now()
      if (now >= tokenData.value.expiresAt) {
        console.log('🔄 Pinia恢复的Token已过期，自动清除')
        clearUser()
      } else {
        console.log('✅ Pinia恢复的Token有效')
        console.log('👤 用户:', user.value?.username)
        console.log('⏰ 剩余时间:', Math.floor((tokenData.value.expiresAt - now) / (1000 * 60)), '分钟')
      }
    }
  }

  return {
    // 状态
    user,
    token,
    tokenData,
    
    // 计算属性
    isAuthenticated,
    isSubscribed,
    
    // 方法
    setUser,
    setToken,
    clearUser,
    fetchUserInfo,
    login,
    logout,
    updateUser,
    getTokenRemainingTime,
    isTokenExpiringSoon,
    refreshToken,
    checkTokenValidity
  }
}, {
  // Pinia持久化配置
  persist: {
    key: 'user-store',
    storage: localStorage,
    // 只持久化需要的状态
    pick: ['user', 'tokenData']
  }
})